<?php

namespace app\api\controller;

use app\api\model\Survey as SurveyModel;
use app\api\model\SurveyQuestion as SurveyQuestionModel;
use app\api\model\SurveyOption as SurveyOptionModel;


/**
 * 问卷
 * Class Shop
 * @package app\api\controller
 */
class Survey extends Controller
{
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function add()
    {
        $input = input();
        // 当前用户信息
        $userInfo = $this->getUser();
        $user_id = $userInfo['user_id'];
        $data['user_id'] = $user_id;
        $data['create_time'] = time();
        $data['answer_text'] = $input['result'];
        $data['survey_id'] = $input['survey_id'];
        if (DB("survey_answer")->insert($data)) {
            return $this->renderSuccess();
        }
    }
    /**
     * 获取问卷列表
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function index()
    {
        // 整理请求的参数
        $param = array_merge($this->request->param(), [
            'is_delete' => 0
        ]);
        // 获取列表数据
        $model = new SurveyModel;
        $list = $model->getList($param, $this->getUser(false));
        return $this->renderSuccess(compact('list'));
    }
    /**
     * 获取详情
     * @param $ID
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($id)
    {
        // 获取用户信息（如果不需要，可以省略）
        $user = $this->getUser(false);
        
        // 获取问卷主信息
        $surveyModel = new SurveyModel();
        $survey = $surveyModel->where('id', $id)->where('is_delete', 0)->find();

        if (!$survey) {
            return $this->renderError('问卷信息不存在');
        }

        // 获取问卷问题和选项
        $questionModel = new SurveyQuestionModel();
        $questions = $questionModel->with(['options' => function($query) {
            $query->where('is_delete', 0); // 过滤已删除的选项
        }])->where('survey_id', $id)->where('is_delete', 0)->select();
        if ($survey['id'] == "36" || $survey['id'] == "38") {
            $survey['is_phone'] = "4006220899";
            $survey['phone_title'] = "医疗投诉电话:4006220899";
        }else{
            $survey['is_phone'] = "";
            $survey['phone_title'] = "";
        }
        // 整理返回数据
        $surveyDetails = [
            'survey' => $survey,
            'questions' => $questions
        ];

        return $this->renderSuccess(compact('surveyDetails'));
    }
}